/****************************************************
          File Name:47-6-client.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 09:20:46 PM CST
*****************************************************/

#include"binary_fifo.h"
#include<string.h>

int main(int argc,char *argv[])
{
    int shmid, xfrs, bytes;
    struct shmseg *shmp;

    shmid=shmget(SHM_KEY,0,0);
    if(shmid==-1)
        err("shmget");

    shmp=shmat(shmid,NULL,0); 
    if(shmp==(void *)-1)
        err("shmat");

    for(xfrs=0, bytes=0;;xfrs++)
    {
		if(Reserved()==-1)
			err("reserved");
		
		if(shmp->cnt==0)
			break;
		bytes+=shmp->cnt;
		
		shmp->cnt=write(STDOUT_FILENO,shmp->buf,BUF_SIZE);
		memset(shmp->buf,'\0',BUF_SIZE);		// clean buf
		if(shmp->cnt==-1)
			err("write");
    }
	
    fprintf(stderr,"Received %d bytes (%d xfrs)\n", bytes, xfrs);
    exit(EXIT_SUCCESS);
}